<?php
/**
 * Provides information, monitoring and logging features
 * @name Info
 */
class BRail_Application_Controller_Info extends BRail_Application_Controller_Abstract
{
    /**
     * Info configuration file
     * @var Zend_Config
     */
    private $_infoConfig;

    /**
     * Initialize context switching
     * @return void
     */
    public function init()
    {
        parent::init();
        $contextSwitch = $this->_helper->getHelper('contextSwitch');
        if (defined('STDIN')) {
            $contextSwitch->addActionContext('index', 'cli');
        }
        $contextSwitch->addActionContext('index', 'xml')
                    ->initContext();
        $this->_infoConfig = $this->_loadIni();
        if ($this->_infoConfig === false) {
            throw new Zend_Exception('info.ini is required to use the info page');
        }
    }

    /**
     * Parse a configuration file
     *
     * Should be called only of PHP contains a bug that won't allow / or any non ASCII character in it
     *
     * @param string $filename The filename of the ini file being parsed.
     * @param boolean $processSections If set to TRUE, the result will be a multidimensional array with section names
     * @return array The settings are returned as an associative array on success, and FALSE on failure.
     */
    protected function _parseIniFile($filename, $processSections = false)
    {
        $result = array();
        $section = null;
        $lineNumber = 0;
        foreach (explode("\n", file_get_contents($filename)) as $line) {
            $line = preg_replace('/(#|;).*/', '', $line); // Remove comments
            $line = trim($line);

            if (empty($line))
                continue;

            if ($line[0] == "[" && $endIdx = strpos($line, "]")) {
                $section = trim(substr($line, 1, $endIdx - 1));
                continue;
            }

            if (preg_match('/(.+)\s*=\s*(.+)/', $line, $matches)) {
                if (null !== $section && $processSections) {
                    $result[$section][$matches[1]] = $matches[2];
                } else {
                    $result[$matches[1]] = $matches[2];
                }
            } else {
                return false;
            }
        }

        return $result;
    }

    /**
     * Load the status.ini file
     * @return Zend_Config
     */
    protected function _loadIni()
    {
        if (file_exists(APPLICATION_PATH . '/configs/info.ini')) {
            if (PHP_VERSION_ID > 50300) {
                return parse_ini_file(APPLICATION_PATH . '/configs/info.ini', true);
            } else {
                return $this->_parseIniFile(APPLICATION_PATH . '/configs/info.ini', true);
            }
        }
        return false;
    }

    /**
     * /info/index
     * @return void
     */
    public function indexAction()
    {
        $this->view->application = $this->_getApplication();

        $brailVersion = BRail_Application_Info::getSvnInfo(ROOT_PATH . '/library/BRail');
        preg_match('/release-(.*)\/BRail$/', $brailVersion['repositoryUrl'], $matches);
        if (count($matches) > 0) {
            $this->view->brailVersion = $matches[1];
            $brailVersionSplit = explode('.', $matches[1]);
            $skeletonVersionSplit = explode('.', $this->_skeletonVersion);
            if ($brailVersionSplit[0] != $skeletonVersionSplit[0]
                    ||
                    $brailVersionSplit[1] != $skeletonVersionSplit[1]) {
                $this->view->frameworkVersionCompare = 'Mismatch between Skeleton and BRail library versions !';
            } else {
                $this->view->frameworkVersionCompare = 'OK';
            }
        } else {
            $this->view->brailVersion = "Unable to retrieve tagged version";
            $this->view->frameworkVersionCompare = "Unable to retrieve tagged BRail library version";
        }
        $this->view->skeletonVersion = $this->_skeletonVersion;

        $phpinfo = BRail_Application_Info::getPhpInfoAsArray();
        $this->view->phpVersion = phpversion();
        $this->view->mysqlVersion = $phpinfo['mysql']['Client API version'];
        $this->view->mysqliVersion = $phpinfo['mysqli']['Client API library version'];
        $this->view->httpdVersion = $_SERVER["SERVER_SOFTWARE"];
        $this->view->osName = php_uname('s');
        $this->view->osVersion = php_uname('r');

        $this->view->filePermissions = BRail_Application_Info::verifyPermissions($this->_infoConfig['files'], false);
        $this->view->directoryPermissions = BRail_Application_Info::verifyPermissions($this->_infoConfig['directories'], true);

        $this->view->network = BRail_Application_Info::verifyNetwork($this->_infoConfig['network']);

        $this->view->svnInfo = BRail_Application_Info::getSvnInfo(ROOT_PATH);

        if (Zend_Registry::isRegistered('Zend_Cache')) {
            $cacheCoreObj = Zend_Registry::get('Zend_Cache');
            $cacheBackendObj = $cacheCoreObj->getBackend();
            if (get_class($cacheBackendObj) == 'Zend_Cache_Backend_File') {
                $cacheDir = $cacheBackendObj->getOption('cache_dir');
                $this->view->cacheStats = array(
                        'cacheDir' => $cacheDir,
                        'percentage' => $cacheBackendObj->getFillingPercentage(),
                        'fileCount' => count(glob($cacheDir . '/*'))
                    );
            }
        }
    }

    /**
     * Clears the Zend_Cache
     * @return void
     */
    public function clearCacheAction()
    {
        $this->_setAjaxOutput();
        if (Zend_Registry::isRegistered('Zend_Cache')) {
            if (Zend_Registry::get('Zend_Cache')->clean()) {
                echo 'OK';
            } else {
                echo 'Failed !';
            }
        }
    }
}